// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

/*
 * @Author: qiulin_JXGM ql1746365080@gmail.com
 * @Date: 2024-10-16 09:35:57
 * @LastEditors: qiulin 1746365080@qq.com
 * @LastEditTime: 2024-12-23 14:56:30
 * @FilePath: \SGFEM\Import\BDFImport\BulkData\Property\PBARLParser.cpp
 */
#include "PBARLParser.h"

#include <cstdint>

#include "boost/algorithm/string/trim.hpp"

#include "Utility/Logging/SGLogger.h"

#include "DBManager/DBServiceFactory.h"
#include "DBManager/IService/Input/Property/IPBARLService.h"

#include "Import/BDFImport/BDFImport.h"
#include "Import/BDFImport/BDFParserBase.h"

BULKDATA_ENTRY_PARSER_REG (PBARL)
using namespace SG::DBManager;
using namespace SG::Import;
using namespace SG::DataStructure;
/*
// file://./../../Doc/MarkDown/BulkData/PBARL/PBARL.md>
*/
namespace
{
    std::map<SG::DataStructure::FEM::BeamSectionStandardTypes, size_t> S_DimSizeMap = {
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_ROD, 1 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_BAR, 2 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_TUBE, 2 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_TUBE2, 2 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_BOX, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_BOX1, 6 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_DBOX, 10 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_I, 6 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_I1, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_H, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_L, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_CHAN, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_CHAN1, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_CHAN2, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_T, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_T1, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_T2, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_CROSS, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_Z, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_HEXA, 3 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_HAT, 4 },
        { SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_HAT1, 5 },
    };
}  // namespace

enum PBARLkey : std::uint8_t
{
    PBARLkey_PID   = 1,  // PBARL条目中的属性识别号索引
    PBARLkey_MID   = 2,  // PBARL条目中的材料识别号索引
    PBARLkey_GROUP = 3,  // PBARL条目中的截面组索引
    PBARLkey_TYPE  = 4,  // PBARL条目中的截面类型索引
};

SG::DataStructure::Common::Status BDF::BULKDATA::ParsePBARL (const std::shared_ptr<SG::DBManager::DBServiceFactory>& dbServiceFactory,
                                                             std::vector<std::string>&                               dividedEntryInfo)
{
    // 创建一个用于存储PBARL数据的临时数据结构体
    SG::DataStructure::FEM::PBARLData tempData;
    tempData.m_dimension.reserve (10);
    // TODO(bug 001) 确认正确的m_domainId
    // 目前硬编码为1，需确认其正确性
    tempData.m_domainId = 1;

    // 从分割后的词条中获取属性ID（PID）并赋值
    tempData.m_id = convertToI64 (dividedEntryInfo[PBARLkey_PID]);

    // 获取材料ID（MID）并赋值
    tempData.m_mId = convertToI64 (dividedEntryInfo[PBARLkey_MID]);

    // 获取截面组（GROUP），如果为空则设置默认值为"MSCBML0"
    std::string groupStr = dividedEntryInfo[PBARLkey_GROUP];
    boost::trim (groupStr);  // 去除字符串两边的空格
    if (groupStr.empty ())   // 如果GROUP字段为空，设置默认值
    {
        groupStr = "MSCBML0";
    }
    // 将GROUP字符串复制到tempData的m_group字段中
    std::strncpy (tempData.m_group, boost::algorithm::trim_copy (groupStr).c_str (), boost::algorithm::trim_copy (groupStr).size ());

    // 获取截面类型（TYPE）并赋值
    std::string typeStr = dividedEntryInfo[PBARLkey_TYPE];
    boost::trim (typeStr);  // 去除字符串两边的空格
    std::strncpy (tempData.m_type, boost::algorithm::trim_copy (typeStr).c_str (), boost::algorithm::trim_copy (typeStr).size ());

    // 根据截面类型计算所需的DIMi数量，使用tempData获取横截面类型
    size_t const dimSize = S_DimSizeMap[tempData.GetBeamSectionStandardTypes ()];

    // 计算词条的行数
    size_t const rowNum = dividedEntryInfo.size () / 10;

    // 查找词条的最后一个非空索引，用于确定条目的结尾
    int judgeRownum = rowNum - 1;
    int lastindex   = findNonEmptyIndex (dividedEntryInfo, judgeRownum);  // 最后一个非空filed的下标
    while (-1 == lastindex)
    {
        judgeRownum--;
        if (judgeRownum < 0)
        {
            throw std::runtime_error ("RBE2Parser: judgeRownum < 0");
        }
        lastindex = findNonEmptyIndex (dividedEntryInfo, judgeRownum);
    }
    // 根据最后一个索引计算DIMi的大小并检查是否存在NSM（非结构质量）

    size_t const entryDimSize =
        lastindex - 6 - 2 * rowNum;  // 词条包含的DIM数量
                                     //=lastindex-10（第一行）-2*（rowNum-2)（除开第一行以最后一行）-1(最后一行)+1(index而非size)
    bool const isHaveNsm = (entryDimSize != dimSize);

    // 如果存在NSM字段，则将其值解析并赋值给tempData
    if (isHaveNsm)
    {
        tempData.m_nsm = convertToReal (dividedEntryInfo[lastindex]);
        lastindex--;
    }

    // 遍历每一行词条，处理维度信息
    for (size_t curRow = 1; curRow < rowNum; curRow++)
    {
        // 遍历每行中的字段
        for (size_t fieldsColumn = 1; fieldsColumn < 9; fieldsColumn++)
        {
            // 计算当前字段在dividedEntryInfo中的索引
            const size_t curIndex  = curRow * 10 + fieldsColumn;
            std::string& curStrKey = dividedEntryInfo[curIndex];

            // 检查当前字段是否为空白
            bool const isEmpty = is_all_space (curStrKey);

            // 如果字段为空白，则跳过
            if (isEmpty)
            {
                continue;
            }

            // 将当前的DIM值添加到tempData的维度列表中
            tempData.m_dimension.push_back (convertToReal (curStrKey));

            // 如果已经到达最后一个非空字段，则结束处理
            if (curIndex == static_cast<size_t> (lastindex))
            {
                break;
            }
        }
    }

    // 处理特殊情况DBX
    if (tempData.GetBeamSectionStandardTypes () == SG::DataStructure::FEM::BeamSectionStandardTypes::BEAMSECTYPE_DBOX)
    {
        switch (tempData.m_dimension.size ())
        {
        case 4:
            tempData.m_dimension.push_back (tempData.m_dimension[3]);  // DIM5、DIM6、DIM7和DIM8的默认值为DIM4。
            tempData.m_dimension.push_back (tempData.m_dimension[3]);
            tempData.m_dimension.push_back (tempData.m_dimension[3]);
            tempData.m_dimension.push_back (tempData.m_dimension[3]);
            tempData.m_dimension.push_back (tempData.m_dimension[3]);  // DIM9和DIM10的默认值为DIM6
            tempData.m_dimension.push_back (tempData.m_dimension[3]);
            break;
        case 8:
            tempData.m_dimension.push_back (tempData.m_dimension[5]);  // DIM9和DIM10的默认值为DIM6
            tempData.m_dimension.push_back (tempData.m_dimension[5]);
        case 10:
            break;
        default:
            throw std::runtime_error ("DBX need 5 or more dimensions!");
            break;
        }
    }

    // 使用数据库服务工厂将解析后的PBARL数据添加到数据库中
    return dbServiceFactory->get<IPBARLService> ()->Add (tempData);
}